package cn.sh.tools.util;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.system.SystemUtil;
import com.google.common.collect.Sets;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description PDF工具
 * @Classname PdfUtils
 * @Date 2023/5/24
 * @Author sh
 **/
public class PdfUtils {

    private static final String SET_FILE = "setFile";
    private static final String GET_NUMBER_OF_PAGES = "getNumberOfPages";
    private static final String GET_PAGE_IMAGE = "getPageImage";
    private static final String DISPOSE = "dispose";

    /**
     * icepdf GitHub地址：https://github.com/pcorless/icepdf
     * <pre>
     * 问题：icepdf 7.0.2 版本依赖的jdk版本是 jdk11。
     *      如果不配置，则运行代码会提示错误信息：【类文件具有错误的版本 55.0, 应为 52.0】。55就是jdk11,52是jdk8。
     * 方案一：将当前整个项目sh-tool在idea中也要配置为jdk11。
     * 方案二：直接使用反射调用，这样就不用配置idea的jdk版本为jdk11了。
     * </pre>
     * 该方法的功能：将pdf转为图片。生成的图片的路径和pdf的路径相同。
     */
    public static String pdfToImage(String pdfPath, String imgSuffix) {
        String jdkVersion = SystemUtil.getJavaInfo().getVersion();
        jdkVersion = jdkVersion.substring(0, jdkVersion.indexOf("."));
        if (!"11".equals(jdkVersion)) {
            return "JDK版本必须是11，否则不处理";
        }
        if (!pdfPath.endsWith(".pdf")) {
            throw new RuntimeException("pdf路径要写文件名");
        }

        //org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
        String documentClassName = "org.icepdf.core.pobjects.Document";
        Class<?> documentClazz = null;
        try {
            documentClazz = Class.forName(documentClassName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        Object doc = ReflectUtil.newInstance(documentClazz);

        Set<String> documentMethodSet = Sets.newHashSet(
                SET_FILE, GET_NUMBER_OF_PAGES, GET_PAGE_IMAGE, DISPOSE);
        List<Method> publicMethods = ReflectUtil.getPublicMethods(documentClazz,
                method -> documentMethodSet.contains(method.getName()));
        Map<String, Method> publicMethodMap = new HashMap<>();
        publicMethods.forEach(method -> publicMethodMap.put(method.getName(), method));
        publicMethods.clear();

        try {
            //document.setFile(pdfPath);
            ReflectUtil.invoke(doc, publicMethodMap.get(SET_FILE), pdfPath);
            //缩放比例，影响输出图片大小
            float scale = 2.0f;
            //旋转角度
            float rotation = 0f;

            String imgName = pdfPath.substring(0, pdfPath.lastIndexOf(".")) + "." + imgSuffix;

            //int numberOfPages = document.getNumberOfPages();
            int numberOfPages = ReflectUtil.invoke(doc, publicMethodMap.get(GET_NUMBER_OF_PAGES));
            for (int i = 0; i < numberOfPages; i++) {
                //BufferedImage image = (BufferedImage)
                //        document.getPageImage(i, org.icepdf.core.util.GraphicsRenderingHints.SCREEN,
                //                org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
                BufferedImage image = ReflectUtil.invoke(doc, publicMethodMap.get(GET_PAGE_IMAGE),
                        i, 1, 2, rotation, scale);
                RenderedImage renderedImage = image;
                try {
                    // 图片转存，也可以直接创建本地文件File进行保存
                    File file = new File(imgName);
                    ImageIO.write(renderedImage, imgSuffix, file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            //document.dispose();
            ReflectUtil.invoke(doc, publicMethodMap.get(DISPOSE));
        }

        return "PDF转图片成功";
    }

}
